package xin.core.jwt;

import xin.common.utils.AssertUtils;
import xin.common.date.LocalDateConverter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import xin.pms.model.Permission;
import xin.pms.model.User;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <pre>
 * Jwt User Factory Bean
 * </pre>
 *
 * @author lixin
 * @version 1.0
 * @since 2017/11/23 10:09
 */
public final class JwtUserFactory {


    public static JwtUser create(User user) {
        HashSet<Permission> permissionSet = user.getAllPermissions();
        List<Permission> permissionList = AssertUtils.isNotNull(permissionSet)
                ? permissionSet.stream().collect(Collectors.toList())
                : new ArrayList<>();
        return new JwtUser(
                user.getId(),
                user.getUserName(),
                user.getPasswordHash(),
                mapToGrantedAuthorities(permissionList),
                !user.getDeleted() && !user.getLocked(),
                user.getLastPasswordResetDate() == null ? null : user.getLastPasswordResetDate()
        );
    }

    private static List<GrantedAuthority> mapToGrantedAuthorities(List<Permission> permissionList) {
        return AssertUtils.isNotNull(permissionList)?permissionList.stream()
                .map(item -> new SimpleGrantedAuthority(item.getCode()))
                .collect(Collectors.toList()):new ArrayList<>();
    }
}